#include "app.h"
#include "tim.h"
#include "bsp_encode.h"
#include "bsp_buzzer.h"
#include "motor/Motor_Control.h"
#include "motor/Emm_V5_UART.h"
#include "remote_control/ps2.h"

PID_Controller Motor_1_PID;
float ref_speed = 0.0f;
uint32_t micoseconds_10 = 0;

void App_Init(void){
    Encoder_Init();

    Motor_Init();

    Emm_V5_Init();

    AX_PS2_Init();

    PID_Init(&Motor_1_PID,19.0f,3.50f,-2.90000f,-9999,9999);

}


void App_process(void){
    Motor_Control(&Motor_1_PID,ref_speed);

    Remote_control();

    HAL_Delay(1);
}





//以下为中断回调函数
//如果遇到报错请在it里面的同名函数前加__weak
//如不了解 __weak 请移步AI


void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim){
    if (htim == &htim6){                                                              //pid计算      0.001s计算一次
        PID_Compute(&Motor_1_PID,Motor_1.speed);
    }else if (htim == &htim7){                                                         //encode采样   0.1s采样一次
        Motor_1.last_ecd = Motor_1.ecd;
        Motor_1.ecd += Encoder_Get();
        Motor_1.speed = (Motor_1.ecd - Motor_1.last_ecd) / 844.0f/0.1f*60.0f;    //单位转/分：rpm
    }else if (htim == &htim17){
        if (micoseconds_10 > 0) micoseconds_10--;
    }
}

void USART3_IRQHandler(void)
{
    /* USER CODE BEGIN USART1_IRQn 0 */
    if(__HAL_UART_GET_FLAG(&huart3, UART_FLAG_IDLE) != RESET)
    {
        __HAL_UART_CLEAR_IDLEFLAG(&huart3); // 清除IDLE标志
        HAL_UART_DMAStop(&huart3); // 停止DMA，为了重新设置DMA发送多少数据
        rxCount = CMD_LEN - __HAL_DMA_GET_COUNTER(&hdma_usart3_rx);
        rxFrameFlag = true; // 置位一帧命令接收完毕标志位
        HAL_UART_Receive_DMA(&huart3, (uint8_t *)rxCmd, CMD_LEN);
    }
    /* USER CODE END USART1_IRQn 0 */
    HAL_UART_IRQHandler(&huart3);
    /* USER CODE BEGIN USART1_IRQn 1 */
    /* USER CODE END USART1_IRQn 1 */
}


